
# 通用的接收服务，不解析字段，只按照\r\n换行存储
import socket
import threading
import logging
from datetime import datetime


# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("logs/wits_a_receiver.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)


class WITSAReceiver:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.socket = None
        self.clients = []
        self.running = False

    def start_server(self):
        """启动WITS-A接收服务器"""
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.bind((self.host, self.port))
            self.socket.listen(5)
            self.running = True
            logger.info(f"WITS-A接收服务器启动在 {self.host}:{self.port}")

            # 启动接受客户端连接的线程
            accept_thread = threading.Thread(target=self.accept_clients)
            accept_thread.daemon = True
            accept_thread.start()

            return True
        except Exception as e:
            logger.error(f"启动服务器失败: {e}")
            return False

    def accept_clients(self):
        """接受客户端连接并为每个客户端启动数据接收线程"""
        while self.running:
            try:
                client_socket, client_address = self.socket.accept()
                logger.info(f"新的客户端连接: {client_address}")
                self.clients.append({
                    "socket": client_socket,
                    "address": client_address,
                    "buffer": b""
                })

                # 为每个客户端启动数据接收线程
                data_thread = threading.Thread(
                    target=self.receive_data_from_client,
                    args=(client_socket, client_address)
                )
                data_thread.daemon = True
                data_thread.start()

            except Exception as e:
                if self.running:
                    logger.error(f"接受客户端连接时出错: {e}")

    def receive_data_from_client(self, client_socket, client_address):
        """从指定客户端接收数据"""
        try:
            logger.info(f"开始从客户端 {client_address} 接收数据")

            buffer = b""
            while self.running:
                try:
                    # 接收数据
                    data = client_socket.recv(1024)
                    if not data:
                        logger.warning(f"客户端 {client_address} 连接已关闭")
                        break

                    buffer += data

                    # 处理完整的数据包 (WITS-A记录以\r\n结尾)
                    while b'\r\n' in buffer:
                        record, buffer = buffer.split(b'\r\n', 1)
                        if record:
                            self.process_record(record, client_address)

                except Exception as e:
                    logger.error(f"从客户端 {client_address} 接收数据时出错: {e}")
                    break

        except Exception as e:
            logger.error(f"与客户端 {client_address} 通信时出错: {e}")
        finally:
            # 从客户端列表中移除
            self.remove_client(client_socket)
            logger.info(f"客户端 {client_address} 已断开连接")

    def process_record(self, record, client_address):
        """处理WITS-A记录"""
        try:
            # 解码记录
            record_str = record.decode('ascii').strip()

            # 保存数据到数据库或文件
            self.save_data(client_address,record_str)

        except Exception as e:
            logger.error(f"处理记录时出错: {e}")

    def save_data(self, client_address,item):
        """保存数据到文件（示例实现）"""
        try:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            client_id = f"{client_address[0]}_{client_address[1]}"
            filename = f"data/wits_a_data_{client_id}_{datetime.now().strftime('%Y%m%d')}.txt"

            with open(filename, "a") as f:

                # 准备数据行
                row = f"{timestamp},{client_id},{item}\n"

                f.write(row)

        except Exception as e:
            logger.error(f"保存数据时出错: {e}")

    def remove_client(self, client_socket):
        """从客户端列表中移除客户端"""
        for client in self.clients:
            if client["socket"] == client_socket:
                self.clients.remove(client)
                client_socket.close()
                break

    def stop_server(self):
        """停止服务器"""
        self.running = False
        if self.socket:
            self.socket.close()
        for client in self.clients:
            client["socket"].close()
        logger.info("WITS-A接收服务器已停止")


def main():
    # 配置服务器信息
    HOST = "0.0.0.0"  # 监听所有接口
    PORT = 5001  # 监听端口

    # 创建接收器实例
    receiver = WITSAReceiver(HOST, PORT)

    try:
        # 启动服务器
        if receiver.start_server():
            print("WITS-A数据接收服务器已启动")
            print("按Ctrl+C停止服务器")

            # 保持主线程运行
            while True:
                pass
    except KeyboardInterrupt:
        print("\n正在停止服务器...")
    finally:
        receiver.stop_server()


if __name__ == "__main__":
    main()
